import './interfaces';

interface QueryParam {
	criteria: object;
	fields: { [field_name: string]: 1 | -1 };
	page_no: number;
	page_size: number;
	query_mode: 1;
	sort: {};
	spaceid: string;
	sql: string;
	systemid: string;
	tablename: string;
}

interface QueryResult {
	query_mode: 1;
	spaceid: string;
	systemid: string;
	tablename: string;
	dataArray: BaseTable[];
}

function query(systemid: string, tablename: string, fields: string[], filter: object, page_size = 0, page_no = 1) {
	return {
		criteria: filter,
		fields: fields.reduce((pre, cur) => {
			pre[cur] = 1;
			return pre;
		}, {}),
		page_no,
		page_size,
		query_mode: 1,
		sort: {},
		spaceid,
		sql: '',
		systemid,
		tablename
	} as QueryParam;
}

async function do_query(q: QueryParam[]) {
	const data = await (send_msg('dbacc.find.intranet', q) as Promise<QueryResult[]>);
	return data.map((d) => {
		return d.dataArray;
	});
}

interface Table1 extends BaseTable {
	// todo
	field1: string;
}

interface Table2 extends BaseTable {
	// todo
	field2: string;
}

interface Message {
	// todo
	[field: string]: any;
}

async function atom(msg: Message, headers: IHeaders) {
	const p1 = query('@systemid', '@tablename1', ['@fields'], msg, 1, 1);
	const p2 = query('@systemid', '@tablename2', ['@fields'], msg, 1, 1);
	const [table1, table2] = await do_query([p1, p2]) as [Table1[], Table2[]];
	return { [table1[0].field1]: table2[0].field2 };
}
